// subpages0/giftCard/cardhome/cardhome.js
var app = getApp();
Page({
  data: {
    sumNum: 0,
    sumPrice: 0
  },
  onLoad: function (e) {
    var that = this;
    if (e && e.title) {
      app.setNavtitle(e.title);
    } else {
      app.setNavtitle('礼品卡');
    }
    if(e&&e.coverid){
      that.setData({
        coverid: e.coverid,
        coverIntoview: 'coverIntoview' + e.coverid
      })
    }

    if (!app.globalData.plumSession) {
      app.plumSessionCallback = plumSession => {
        that.requestIndex();
      }
    } else {
      that.requestIndex();
    }
  },
  onShow: function () {
    var that = this;
    that.requestpayType();
  },
  onPullDownRefresh: function () {
    var that = this;
    that.requestIndex();
  },
  requestIndex: function () {
    var that = this;
    wx.showLoading({
      title: '加载中',
    })
    wx.request({
      url: app.globalData.requestUrl,
      data: {
        map: 'applet_giftcard_index_list'
      },
      success: function (res) {
        console.log(res.data);
        if (res.data.ec == 200) {
          var dataInfo = res.data.data;
          var cardList = dataInfo.cardList;
          for (var i = 0; i < cardList.length;i++){
            cardList[i].cartnum = 0;
          }
          that.setData({
            cardCoverlist: dataInfo.coverList,
            cardList: cardList
          })
          console.log(that.data.cardList)
        } else {
          that.setData({
            cardList:[]
          })
          app.errorTip(that, res.data.em, 2000);
        }
      },
      complete: function () {
        wx.hideLoading();
        wx.stopPullDownRefresh();
      }
    });
  },
  requestpayType: function () {
    var that = this;
    wx.showLoading({
      title: '正在加载'
    })
    wx.request({
      url: app.globalData.requestUrl,
      data: {
        map: 'applet_pay_cfg'
      },
      success: function (res) {
        console.log(res.data);
        if (res.data.ec == 200) {
          var payWay = that.data.payWay;
          if (!payWay) {
            payWay = res.data.data ? res.data.data[0].type : 1
          }
          that.setData({
            payType: res.data.data,
            payWay: payWay
          })
        } else {
          console.log(res.data)
          that.setData({
            payType: []
          })
        }
      },
      complete: function () {
        wx.hideLoading();
      }
    });
  },
  // 选择支付方式
  payRadioChange: function (e) {
    this.setData({
      payWay: e.detail.value
    })
    console.log(this.data.payWay);
  },
  showPaychoose: function () {
    var that = this;
    that.setData({
      isShowpaychoose: true
    })
  },
  hidePaychoose:function(){
    var that = this;
    that.setData({
      isShowpaychoose:false
    })
  },
  // 选择封面
  chooseCardcover:function(e){
    var that = this;
    var coverid = e.currentTarget.dataset.id;
    that.setData({
      coverid: coverid,
      coverIntoview: 'coverIntoview' + coverid
    })
  },
  // 加减购物车
  changeNum:function(e){
    var that = this;
    var type = e.currentTarget.dataset.type;
    var id = e.currentTarget.dataset.id;
    var cardList = that.data.cardList;
    for (var i = 0; i < cardList.length;i++){
      if (id == cardList[i].id){
        let curNum = cardList[i].cartnum;
        if (type == 'add') {
          curNum++;
          that.setData({
            [`cardList[${i}].cartnum`]: curNum
          })
          if (that.data.isShowDetail){
            that.hideDetailmodal();
          }
        } else if (type == 'minus'){
          if (cardList[i].cartnum>0){
            curNum--;
            that.setData({
              [`cardList[${i}].cartnum`]: curNum
            })
          }
        }
      }
    }
    var cartList = [];
    for (var i = 0; i < cardList.length; i++) {
      if (cardList[i].cartnum>0){
        var cartObj = {
          id: cardList[i].id,
          name: cardList[i].name,
          cover: cardList[i].cover,
          num: cardList[i].cartnum,
          price: cardList[i].price
        }
        cartList.push(cartObj)
      }
    }
    that.setData({
      cartList: cartList
    })
    that.getSumtotal();
  },
  // 获取总价格，总数量
  getSumtotal:function(){
    var that = this;
    var cartList = that.data.cartList ? that.data.cartList:[];
    var sumNum = 0,sumPrice = 0;
    if (cartList.length>0){
      for (var i = 0; i < cartList.length; i++) {
        if (cartList[i].num > 0) {
          sumNum += cartList[i].num;
          sumPrice += cartList[i].num * cartList[i].price;
        }
      }
    }else{
      that.setData({
        isShowCart:false
      })
    }
    that.setData({
      sumNum: sumNum,
      sumPrice: sumPrice.toFixed(2)
    })
  },
  // 清空购物车
  clearCart:function(){
    var that = this;
    var cardList = that.data.cardList;
    wx.showModal({
      title: '提示',
      content: '确定清空购物车吗？',
      success(res) {
        if (res.confirm) {
          for (var i = 0; i < cardList.length;i++){
            that.setData({
              [`cardList[${i}].cartnum`]: 0
            })
          }
          that.setData({
            cartList:[]
          })
          that.getSumtotal();
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  // 卡详情弹窗
  showDetailmodal:function(e){
    var that = this;
    var cardDetail = e.currentTarget.dataset.cardinfo;
    that.setData({
      cardDetail: cardDetail,
      isShowDetail: true
    })
  },
  hideDetailmodal: function () {
    var that = this;
    that.setData({
      isShowDetail: false
    })
  },
  // 购物车弹窗
  showCartmodal: function () {
    var that = this;
    if (that.data.sumNum > 0) {
      that.setData({
        isShowCart: !that.data.isShowCart
      })
    }
  },
  hideCartmodal: function () {
    var that = this;
    that.setData({
      isShowCart: false
    })
  },
  // 阻止弹窗下面页面滑动
  stopProp:function(e){
    console.log(e);
  },
  nowbuy:function(){
    var that = this;
    if (that.data.sumNum>0){
      that.showPaychoose();
    }
  },
  nowPay:function(){
    var that = this;
    wx.showModal({
      title: '提示',
      content: '确定立即支付吗？',
      success(res) {
        if (res.confirm) {
          that.setData({
            isShowpaychoose:false
          })
          that.confirmBuy();
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  confirmBuy: function () {
    var that = this;
    var data = {
      map:'applet_giftcard_submit_trade',
      coverId: that.data.coverid,
      payType: that.data.payWay ? that.data.payWay:1,
      buyInfo: that.data.cartList ? JSON.stringify(that.data.cartList):''
    }
    console.log(data);
    wx.showLoading({
      title: '正在加载'
    })
    wx.request({
      url: app.globalData.requestUrl,
      data: data,
      success: function (res) {
        console.log(res.data);
        if (res.data.ec == 200) {
          var dataInfo = res.data.data;
          if (dataInfo.status=='dzf'){
            that.orderPay(dataInfo.tid);
          }else{
            that.clearPayorder();
            wx.navigateTo({
              url: '/subpages0/giftCard/cardOrderlist/cardOrderlist'
            })
          }
        } else {
          console.log(res.data)
          app.errorTip(that, res.data.em, 2000);
        }
      },
      complete: function () {
        wx.hideLoading();
      }
    });
  },
  orderPay: function (tid) {
    var that = this;
    var data = {};
    data.map = 'applet_other_trade_pay';
    data.tid = tid;
    //发起请求，获取列表列表
    wx.showLoading({
      title: '加载中',
    })
    wx.request({
      url: app.globalData.requestUrl,
      data: data,
      success: function (res) {
        if (res.data.ec == 200) {
          console.log(res.data.data);
          var dataParam = res.data.data;
          wx.requestPayment({
            'appId': dataParam.appId,
            'timeStamp': dataParam.timeStamp,
            'nonceStr': dataParam.nonceStr,
            'package': dataParam.package,
            'signType': dataParam.signType,
            'paySign': dataParam.paySign,
            'success': function (res) {
              wx.showModal({
                title: '提示',
                content: '支付成功',
                showCancel: false,
                success: function (res) {
                  if (res.confirm) {
                    wx.showLoading({
                      title: '加载中',
                    })
                    setTimeout(function () {
                      wx.hideLoading();
                      that.clearPayorder();
                      wx.navigateTo({
                        url: '/subpages0/giftCard/cardOrderlist/cardOrderlist'
                      })
                    }, 1000)
                  }
                }
              })
            },
            'fail': function (res) {
              console.log(res);
            }
          });
        } else {
          app.errorTip(that, res.data.em, 2000);
        }
      },
      complete: function () {
        wx.hideLoading();
      }
    });
  },
  clearPayorder:function(){
    var that = this;
    that.setData({
      sumNum: 0,
      sumPrice: 0,
      cartList:[],
      isShowpaychoose:false
    })
    that.requestIndex();
  },
  toRecharge: function () {
    wx.navigateTo({
      url: '/subpages/walletRecharge/walletRecharge',
    })
  },
})